package com.jtech.together.view.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;

import com.jtech.together.R;
import com.jtech.together.model.CommentModel;
import com.jtech.together.model.TrendsModel;
import com.jtech.together.model.UserModel;
import com.jtech.together.model.event.TrendsEvent;
import com.jtech.together.mvp.contract.TrendsDetailContract;
import com.jtech.together.mvp.presenter.TrendsDetailPresenter;
import com.jtech.together.util.ActivityJump;
import com.jtech.together.util.Bus;
import com.jtech.together.util.ImageGallery;
import com.jtech.together.util.LocationSelect;
import com.jtech.together.view.activity.base.BaseActivity;
import com.jtech.together.view.adapter.CommentAdapter;
import com.jtech.together.view.adapter.TrendsAdapter;
import com.jtech.together.view.weight.EmojiKeyboard;
import com.jtech.together.view.weight.dialog.CustomProgressDialog;
import com.jtechlib2.listener.OnLoadListener;
import com.jtechlib2.view.JRecyclerView;
import com.jtechlib2.view.RefreshLayout;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.dreamtobe.kpswitch.util.KPSwitchConflictUtil;
import cn.dreamtobe.kpswitch.util.KeyboardUtil;
import cn.dreamtobe.kpswitch.widget.KPSwitchPanelFrameLayout;

/**
 * 动态详情
 * Created by wuxubaiyang on 2017/5/16.
 */
public class TrendsDetailActivity extends BaseActivity implements TrendsDetailContract.View, View.OnClickListener,
        RefreshLayout.OnRefreshListener, OnLoadListener, CommentAdapter.OnCommentListener, TrendsAdapter.OnTrendsListener, TextWatcher,
        KPSwitchConflictUtil.SwitchClickListener, KeyboardUtil.OnKeyboardShowingListener {
    public static final String KEY_TRENDS_ID = "keyTrendsId";

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.refreshlayout_trends_detail)
    RefreshLayout refreshLayout;
    @Bind(R.id.jrecyclerview_trends_detail)
    JRecyclerView jRecyclerView;
    @Bind(R.id.imagebutton_trends_comment_emoji)
    ImageButton imageButtonEmoji;
    @Bind(R.id.imagebutton_trends_comment_send)
    ImageButton imageButtonSend;
    @Bind(R.id.edittext_trends_comment_input)
    EditText editTextInput;
    @Bind(R.id.emojikeyboard_trends_comment)
    EmojiKeyboard emojiKeyboard;
    @Bind(R.id.panellayout_trends_comment)
    KPSwitchPanelFrameLayout switchPanelLayout;

    private TrendsDetailContract.Presenter presenter;
    private InputMethodManager inputMethodManager;
    private CommentAdapter commentAdapter;

    @Override
    protected void initVariables(Bundle bundle) {
        //上车
        Bus.getOn(this);
        //绑定P类
        presenter = new TrendsDetailPresenter(getActivity(), this, bundle);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_trends_detail);
        //实例化键盘管理
        this.inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //设置标题栏
        setSupportActionBar(toolbar);
        //设置后退按钮点击事件
        toolbar.setNavigationOnClickListener(this);
        //设置layoutmanager
        jRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        //设置适配器
        commentAdapter = new CommentAdapter(getActivity());
        jRecyclerView.setAdapter(commentAdapter);
        //默认从第0页开始
        commentAdapter.setStartPage(0);
        //设置加载更多
        jRecyclerView.setLoadMore(true);
        //设置发送按钮默认为不可选
        imageButtonSend.setEnabled(false);
        //设置下拉刷新监听
        refreshLayout.setOnRefreshListener(this);
        //设置加载更多监听
        jRecyclerView.setOnLoadListener(this);
        //设置评论监听
        commentAdapter.setOnCommentListener(this);
        //设置动态监听
        commentAdapter.setOnTrendsListener(this);
        //将输入框与表情键盘绑定
        emojiKeyboard.setupTargetInput(editTextInput);
        //设置输入框的输入监听
        editTextInput.addTextChangedListener(this);
        //监控键盘状态
        KeyboardUtil.attach(getActivity(), switchPanelLayout, this);
        //处理面板与键盘
        KPSwitchConflictUtil.attach(switchPanelLayout, imageButtonEmoji, editTextInput, this);
    }

    @Override
    protected void loadData() {
        refreshLayout.startRefreshing();
    }

    @Override
    public void onClick(View v) {
        //后退
        finish();
    }

    @Override
    public void onBackPressed() {
        if (switchPanelLayout.getVisibility() == View.VISIBLE) {
            switchPanelLayout.setVisibility(View.GONE);
            imageButtonEmoji.setSelected(false);
            return;
        }
        super.onBackPressed();
    }

    /**
     * 还原输入框
     */
    private void resetInput() {
        //发送成功则清空输入框
        editTextInput.setText("");
        //夺取输入框焦点
        editTextInput.clearFocus();
        //关闭软键盘
        inputMethodManager.hideSoftInputFromWindow(editTextInput.getWindowToken(), 0);
        //关闭panel
        switchPanelLayout.setVisibility(View.GONE);
        //设置表情按钮为未选中状态
        imageButtonEmoji.setSelected(false);
    }

    /**
     * 滚动到第一条评论
     */
    private void scrollToFirstComment() {
        jRecyclerView.scrollToPosition(1);
    }

    /**
     * 评论发送按钮
     */
    @OnClick(R.id.imagebutton_trends_comment_send)
    public void onCommentSendClick() {
        String content = editTextInput.getText().toString();
        if (TextUtils.isEmpty(content)) {
            Snackbar.make(toolbar, "评论不能为空", Snackbar.LENGTH_SHORT).show();
            return;
        }
        TrendsModel trendsModel = commentAdapter.getTrendsModel();
        if (null == trendsModel) {
            Snackbar.make(toolbar, "动态为空，数据未加载完成", Snackbar.LENGTH_SHORT).show();
            return;
        }
        CustomProgressDialog.showProgressDialog(getActivity(), "正在发布评论");
        presenter.publishComment(content, trendsModel);
    }

    /**
     * 动态事件变化监听
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void TrendsChange(TrendsEvent event) {
        commentAdapter.updateTrends(event);
    }

    @Override
    public void onClickSwitch(boolean switchToPanel) {
        imageButtonEmoji.setSelected(switchToPanel);
        if (switchToPanel) {
            scrollToFirstComment();
        }
    }

    @Override
    public void onKeyboardShowing(boolean isShowing) {
        if (isShowing) {
            imageButtonEmoji.setSelected(false);
            scrollToFirstComment();
        }
    }

    @Override
    public void onAvatarClick(String userObjectId) {
        Bundle bundle = new Bundle();
        bundle.putString(UserProfileActivity.KEY_USER_OBJECT_ID, userObjectId);
        ActivityJump.build(getActivity(), UserProfileActivity.class)
                .addBundle(bundle)
                .jump();
    }

    @Override
    public void onUpClick(TrendsModel trendsModel, boolean isUp) {
        CustomProgressDialog.showProgressDialog(getActivity(), "点赞");
        presenter.like(trendsModel, isUp ? -1 : 1);
    }

    @Override
    public void onDownClick(TrendsModel trendsModel, boolean isDown) {
        CustomProgressDialog.showProgressDialog(getActivity(), "点赞");
        presenter.unlike(trendsModel, isDown ? -1 : 1);
    }

    @Override
    public void onCommentClick(TrendsModel trendsModel) {
        if (switchPanelLayout.getVisibility() == View.GONE) {
            //弹出输入框
            KeyboardUtil.showKeyboard(editTextInput);
        }
    }

    @Override
    public void onLocationClick(BmobGeoPoint location, UserModel userModel, String describe) {
        LocationSelect.showTarget(getActivity(), new double[]{location.getLatitude(), location.getLongitude()},
                userModel.getNickname() + "\t在这里!", describe);
    }

    @Override
    public void onImageClick(List<String> images, int index) {
        ImageGallery.gallery(getActivity(), new ArrayList<>(images), index);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        imageButtonSend.setEnabled(s.length() > 0);
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    @Override
    public void operationSuccess(TrendsModel trendsModel) {
        CustomProgressDialog.dismissProgressDialog();
    }

    @Override
    public void operationFail(String error) {
        CustomProgressDialog.dismissProgressDialog();
        Snackbar.make(refreshLayout, error, Snackbar.LENGTH_SHORT).show();
    }

    @Override
    public void publishSuccess(CommentModel commentModel) {
        CustomProgressDialog.dismissProgressDialog();
        commentAdapter.addComment(commentModel);
        //还原输入框
        resetInput();
    }

    @Override
    public void publishFail(String error) {
        CustomProgressDialog.dismissProgressDialog();
        Snackbar.make(toolbar, error, Snackbar.LENGTH_SHORT).show();
    }

    @Override
    public void onRefresh() {
        presenter.loadTrends();
        presenter.loadComments(commentAdapter.getPage(false), commentAdapter.getDisplayNumber(), false);
    }

    @Override
    public void loadMore() {
        presenter.loadComments(commentAdapter.getPage(true), commentAdapter.getDisplayNumber(), true);
    }

    @Override
    public void loadTrendsSuccess(TrendsModel trendsModel) {
        refreshLayout.refreshingComplete();
        commentAdapter.setTrendsDetail(trendsModel);
    }

    @Override
    public void loadCommentSuccess(List<CommentModel> commentList, boolean loadMore) {
        refreshLayout.refreshingComplete();
        if (commentList.size() > 0) {
            commentAdapter.setDatas(commentList, loadMore);
            jRecyclerView.setLoadCompleteState();
        } else {
            jRecyclerView.setLoadFinishState();
        }
    }

    @Override
    public void loadFail(String error) {
        refreshLayout.refreshingComplete();
        Snackbar.make(toolbar, error, Snackbar.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //下车
        Bus.getOff(this);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(TAG);
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);
        MobclickAgent.onPause(this);
    }
}